import http from '@/service/base.js';
const debug = process.env.NODE_ENV !== 'production';
import { MessageBox, Message } from 'element-ui';

const BASE_URL = '/api'
const API = {
    signin: '/signin',
    login: '/login',
    list: '/list',
    create: '/create',
    answer: '/answer',
    questionDetails: '/questionDetails',
    like: '/like',
    logout: '/logout'
}

const GETAPI = {}

const UPLOADAPI = {}

const methods = {}

// 根据API key值生成调用方法
Object.keys(API).map((key, index) => {
    methods[key] = (param = {}, callback = () => { }) => {
        return new Promise((resolve, reject) => {
            response((p => {
                let url = BASE_URL + API[key];
                return http.post(url, p)
            })(param), callback).then(([code, res]) => {
                resolve(res)
            })
        })
    }
})

// GET请求方法集合
Object.keys(GETAPI).forEach((key, index) => {
    methods[key] = async (param = {}, callback = () => { }) => {
        let [code, res] = await response((p => {
            let url = BASE_URL + GETAPI[key] + '/' + p;
            return http.get(url)
        })(param), callback)
        return res;
    }
})

Object.keys(UPLOADAPI).forEach((key) => {
    methods[key] = async (param = {}, callback = () => { }) => {
        let [code, res] = await response((p => {
            let url = BASE_URL + UPLOADAPI[key];
            let config = {
                headers: {
                    "Content-Type": "multipart/form-data"
                }
            }
            return http.post(url, p, config)
        })(param), callback)
        return res;
    }
})

function response(promise, callback) {
    return new Promise((resolve, reject) => {
        promise.then(res => {
            if (res.status === 200 && res.data.code == 0) {
                resolve([res.status, res.data])
            } else if (res.data.code === 5000) {
                window.sessionStorage.removeItem('token');
                MessageBox.confirm({
                    title: '确认',
                    message: res.data.message
                }).then(result => {
                    debug ? window.location.replace('./signin.html') : window.location.replace('/')
                }).catch(err => {
                    console.log(err)
                })
                // window.location.replace('http://zjyeytest.17wanxiao.com')
            } else {
                Message.error({
                    message: res.data.message
                })
            }
        }).catch(error => {
            console.log(error)
            // document.title = ''
            // window.location.href = './fail.html'
            // console.log(qs.parse(error))
        })
    })
}

export default methods